﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using eJack.Utility;

namespace eJack.Mortgage.Tool
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();

			Lang = eLanguage.English;
		}

		public bool IsFloat(string sinput)
		{
			bool isYes = true;

			if (CxUtils.NotEmpty(sinput))
			{
				float fresult;
				isYes = float.TryParse(sinput.Trim(), out fresult);
			}
			else
			{
				isYes = false;
			}
			return isYes;
		}

		bool isClickHMYB = false;
		bool isClickWCIA = false;

		#region [ -- Monthly Payment Caculator -- ]

		private void btnMPC_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				float fRate = 0.0f, fTerm = 0.0f, fLoan = 0.0f;

				bool isok = true;
				isok = this.CheckTextBox(this.txtMPC_LoanAmount, this.Lang == eLanguage.English ? "Loan Amount" : "贷款总额", out fLoan);
				isok = isok && this.CheckTextBox(this.txtMPC_Interest, this.Lang == eLanguage.English ? "Rate" : "利息", out fRate);
				isok = isok && this.CheckTextBox(this.txtMPC_TermYears, this.Lang == eLanguage.English ? "Term" : "年期", out fTerm);

				if (isok)
				{
					string serror = string.Empty;
					var fPmt = CxMortgage.CaculateMonthlyPayment(fLoan, fRate, fTerm, out serror);

					if (CxUtils.IsEmpty(serror))
					{
						var sresult = string.Format("{0}: {1}", (this.Lang == eLanguage.English ? "Monthly Payment" : "每月付款"), fPmt.ToString("C"));
						this.txtMPC_Result.Text = sresult;

						//this.ShowMessage(string.Format("Your monthly payment for the \nloan amount of ${0} \nat {1}% \nfor the term of {2} years \nis {3}. ",
						//	fLoan, fRate, fTerm, fresult), MessageBoxImage.Information);
						var smsgFormat = (this.Lang == eLanguage.English ? "Loan amount: {0} \nInterest rate: {1}% \nTerm: {2} years \nMonthly Payment: {3} " : "贷款总额: {0} \n利息: {1}% \n年期: {2} 年 \n每月付款: {3} ");
						this.ShowMessage(string.Format(smsgFormat, fLoan.ToString("C"), fRate, fTerm, fPmt.ToString("C")), MessageBoxImage.Information);

						if (!isClickHMYB)
						{
							this.txtHMYB_Interest.Text = this.txtMPC_Interest.Text;
							this.txtHMYB_TermYears.Text = this.txtMPC_TermYears.Text;
						}

						if (!isClickWCIA)
						{
							this.txtWCIA_Interest.Text = this.txtMPC_Interest.Text;
							this.txtWCIA_TermYears.Text = this.txtMPC_TermYears.Text;
						}
					}
					else
					{
						throw new Exception(serror);
					}
				}
			}
			catch (Exception ex)
			{
				ShowMessage(ex.Message, MessageBoxImage.Warning);
			}
		}

		private void btnMPC_Schedule_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				float fLoan = 0.0f, fExtra = 0.0f, fRate = 0.0f, fTerm = 0.0f;
				string sdate_loan = this.dpMPC_DateLoan.Text;
				var dtLoan = DateTime.Now;
				try
				{
					DateTime.TryParse(sdate_loan, out dtLoan);
				}
				catch (Exception ex) { }

				bool isok = true;
				isok = this.CheckTextBox(this.txtMPC_LoanAmount, this.Lang == eLanguage.English ? "Loan Amount" : "贷款总额", out fLoan);
				isok = isok && this.CheckTextBox(this.txtMPC_Interest, this.Lang == eLanguage.English ? "Rate" : "利息", out fRate);
				isok = isok && this.CheckTextBox(this.txtMPC_TermYears, this.Lang == eLanguage.English ? "Term" : "年期", out fTerm);
				isok = isok && this.CheckTextBox(this.txtMPC_ExtraPayment, this.Lang == eLanguage.English ? "Extra Payment" : "每月额外付款", out fExtra);

				if (isok)
				{
					string serror = string.Empty;
					var fPmt = CxMortgage.CaculateMonthlyPayment(fLoan, fRate, fTerm, out serror);

					if (CxUtils.IsEmpty(serror))
					{
						var sresult = string.Format("{0}: {1}", (this.Lang == eLanguage.English ? "Monthly Payment" : "每月付款"), fPmt.ToString("C"));
						this.txtMPC_Result.Text = sresult;
					}
					else
					{
						throw new Exception(serror);
					}

					//var skey = string.Format("{0}-{1}-{2}-{3}-{4}-{5}", fLoan, fPmt, fExtra, fRate, fTerm, dtLoan);
					var psw = new PaymentScheduleWindow(fLoan, fPmt, fExtra, fRate, fTerm, dtLoan, this.Lang);
					psw.ShowDialog();
				}
			}
			catch (Exception ex)
			{
				ShowMessage(ex.Message, MessageBoxImage.Warning);
			}
		}

		#endregion

		#region [-- How much can i borrow -- ]

		private void btnHMYB_Click(object sender, RoutedEventArgs e)
		{
			isClickHMYB = true;
			try
			{
				float fSalary = 0.0f, fDebt = 0.0f, fPrice = 0.0f, fDown = 0.0f, fRate = 0.0f, fYear = 0.0f, fTax = 0.0f, fInsurance = 0.0f;

				bool isok = true;
				isok = this.CheckTextBox(this.txtHMYB_AnnualSalary, this.Lang == eLanguage.English ? "Annual Salary" : "年薪", out fSalary);
				isok = isok && this.CheckTextBox(this.txtHMYB_MonthlyDebt, this.Lang == eLanguage.English ? "Monthly Debt" : "每月负债", out fDebt);
				isok = isok && this.CheckTextBox(this.txtHMYB_PurchasePrice, this.Lang == eLanguage.English ? "Purchase Price" : "房产价格", out fPrice);
				isok = isok && this.CheckTextBox(this.txtHMYB_Interest, this.Lang == eLanguage.English ? "Rate" : "利息", out fRate);
				isok = isok && this.CheckTextBox(this.txtHMYB_DownPayment_Amount, this.Lang == eLanguage.English ? "Down payment" : "预付款", out fDown);

				if (isok)
				{
					if (fDown <= 0.0f)
					{
						if (IsFloat(this.txtHMYB_DownPayment_Percent.Text))
						{
							var fpercent = CxFloat.ParseFloat(this.txtHMYB_DownPayment_Percent.Text, 0.0f);
							this.txtHMYB_DownPayment_Amount.Text = ((int)(fPrice * fpercent * 0.01)).ToString("C").Replace("$", "").Replace(".00", "");

							isok = isok && this.CheckTextBox(this.txtHMYB_DownPayment_Amount, this.Lang == eLanguage.English ? "Down payment" : "预付款", out fDown);
						}
					}
					else
					{
						this.txtHMYB_DownPayment_Percent.Text = "0";
					}
				}
				isok = isok && this.CheckTextBox(this.txtHMYB_TermYears, this.Lang == eLanguage.English ? "Terms" : "年期", out fYear);
				isok = isok && this.CheckTextBox(this.txtHMYB_YearlyTax, this.Lang == eLanguage.English ? "Yearly Tax" : "房产税", out fTax);
				isok = isok && this.CheckTextBox(this.txtHMYB_YearlyInsurance, this.Lang == eLanguage.English ? "Yearly Insurance" : "房产保险", out fInsurance);

				if (isok)
				{
					string serror = string.Empty;

					float fpayment_month = 0.0f, ftotal = 0.0f;
					var fHMB = CxMortgage.CaculateHowMuchBorrow(fSalary, fDebt, fPrice, fRate, fDown, fYear, fTax, fInsurance, out fpayment_month, out ftotal, out serror);

					if (CxUtils.IsEmpty(serror))
					{
						string smsgFormat = this.Lang == eLanguage.English ? "You can afford: {0}, Monthly pay: {1}, Total P&I: {2}" : "你的贷款能力: {0}, 每月付款: {1}, 本利和: {2}";

						string sresult = string.Format(smsgFormat, fHMB.ToString("C"), fpayment_month.ToString("C"), ftotal.ToString("C"));
						this.txtHMYB_Result.Text = sresult;

						smsgFormat = this.Lang == eLanguage.English ? "You can afford: {0} \n Your monthly payment is: {1}% \nTotal P&I is: {2} " : "你的贷款能力: {0} \n每月付款: {1} \n本利和: {2}";
						this.ShowMessage(string.Format(smsgFormat, fHMB.ToString("C"), fpayment_month.ToString("C"), ftotal.ToString("C")), MessageBoxImage.Information);
					}
					else
					{
						throw new Exception(serror);
					}
				}
			}
			catch (Exception ex)
			{
				ShowMessage(ex.Message, MessageBoxImage.Warning);
			}
		}

		#endregion

		#region [-- What can i afford -- ]

		private void btnWCIA_Click(object sender, RoutedEventArgs e)
		{
			isClickWCIA = true;
			try
			{
				float fPayment = 0.0f, fRate = 0.0f, fTerm = 0.0f;

				bool isok = true;
				isok = this.CheckTextBox(this.txtWCIA_DesireMonthPayment, this.Lang == eLanguage.English ? "Desired Monthly Payment" : "每月期望付款额", out fPayment);
				isok = isok && this.CheckTextBox(this.txtWCIA_Interest, this.Lang == eLanguage.English ? "Rate" : "利息", out fRate);
				isok = isok && this.CheckTextBox(this.txtWCIA_TermYears, this.Lang == eLanguage.English ? "Terms" : "年期", out fTerm);

				if (isok)
				{
					string serror = string.Empty;
					var fWCIA = CxMortgage.CaculateWhatCanIAfford(fPayment, fRate, fTerm, out serror);

					if (CxUtils.IsEmpty(serror))
					{
						// str= "<font color=red>Your loan will be for the amount of <b>$" +fStr +"</b>" +
						//  " at " +cF.Rate.value +"%" +
						//  " for the term of " +cF.Term.value +
						//  " years with monthly payments of $" +fPmt +"</font>";
						//}

						string smsgFormat = this.Lang == eLanguage.English ? "Your loan will be {0}" : "你的贷款能力: {0}";
						string sresult = string.Format(smsgFormat, fWCIA.ToString("C"));
						this.txtWCIA_Result.Text = sresult;

						this.ShowMessage(string.Format(smsgFormat, fWCIA.ToString("C")), MessageBoxImage.Information);
					}
					else
					{
						throw new Exception(serror);
					}
				}
			}
			catch (Exception ex)
			{
				ShowMessage(ex.Message, MessageBoxImage.Warning);
			}
		}

		#endregion

		private void ShowMessage(string smessage, MessageBoxImage mbi)
		{
			string scaption = mbi == MessageBoxImage.None ? "" : (mbi == MessageBoxImage.Information ? "Information" : mbi.ToString());
			MessageBox.Show(smessage, scaption, MessageBoxButton.OK, mbi);
		}

		private bool CheckTextBox(TextBox tb, string sobjectName, out float fvalue)
		{
			fvalue = 0.0f;
			if (IsFloat(tb.Text))
			{
				fvalue = CxFloat.ParseFloat(tb.Text, 0.0f);
				return true;
			}
			else
			{
				MessageBox.Show(string.Format("{0} {1}.", sobjectName, this.Lang == eLanguage.English ? "is invalid" : "无效"), "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
				tb.Focus();
				return false;
			}
		}

		#region [ -- event handler -- ]

		private void onTermYears_LostFocus(object sender, RoutedEventArgs e)
		{
			var tb = sender as TextBox;
			if (null != tb)
			{
				var stext = tb.Text.Replace(",", "");
				if (!this.IsFloat(stext))
				{
					tb.Text = "30";
				}
			}
		}

		private void onMoney_LostFocus(object sender, RoutedEventArgs e)
		{
			var tb = sender as TextBox;
			if (null != tb)
			{
				try
				{
					var stext = tb.Text.Replace(",", "");
					if (this.IsFloat(stext))
					{
						var ftext = CxFloat.ParseFloat(stext, 0.0f);
						tb.Text = ftext.ToString("C").Replace("$", "").Replace(".00", "");
					}
					else
					{
						tb.Text = "0";
					}

					//try
					//{
					//	if (tb == this.txtHMYB_DownPayment_Percent)
					//	{
					//		if (IsFloat(this.txtHMYB_DownPayment_Percent.Text) && IsFloat(this.txtHMYB_PurchasePrice.Text))
					//		{
					//			var fprice = CxFloat.ParseFloat(this.txtHMYB_PurchasePrice.Text, 0.0f);
					//			var fpercent = CxFloat.ParseFloat(this.txtHMYB_DownPayment_Percent.Text, 0.0f);

					//			this.txtHMYB_DownPayment_Amount.Text = ((int)(fprice * fpercent * 0.01)).ToString("C").Replace("$", "").Replace(".00", "");
					//		}
					//	}
					//}
					//catch (Exception ex) { }
				}
				catch (Exception ex)
				{
					string sname = tb.Name;
					ShowMessage(string.Format("LostFocus - onMoney - {0}\n{1}", sname, ex.Message), MessageBoxImage.Error);
				}
			}
		}

		private void onInterest_LostFocus(object sender, RoutedEventArgs e)
		{
			var tb = sender as TextBox;
			if (null != tb)
			{
				var stext = tb.Text.Replace(",", "");
				if (!this.IsFloat(stext))
				{
					tb.Text = "";
				}
			}
		}

		#endregion

		public eLanguage Lang { get; set; }

		private void onRadioButton_Checked(object sender, RoutedEventArgs e)
		{
			var cb = sender as RadioButton;
			if (null != cb)
			{
				var skey = cb.Content.ToString();
				if ((skey.Equals("English", StringComparison.OrdinalIgnoreCase) || skey.Equals("英文", StringComparison.OrdinalIgnoreCase)) && this.Lang != eLanguage.English)
				{
					updateLanguage(eLanguage.English);
				}
				else if ((skey.Equals("Chinese", StringComparison.OrdinalIgnoreCase) || skey.Equals("中文", StringComparison.OrdinalIgnoreCase)) && this.Lang != eLanguage.Chinese)
				{
					updateLanguage(eLanguage.Chinese);
				}

			}
		}

		private void updateLanguage(eLanguage eLang)
		{
			Lang = eLang;

			if (eLang == eLanguage.Chinese)
			{
				this.Title = "贷款计算器 v1.0 - 杰克帝";

				this.lang_en.Content = "英文";
				this.lang_cn.Content = "中文";

				// monthly payment & schedule
				//
				this.mpc_header.Text = "月还款计算 & 时间表";
				//this.mpc_tip.Content = "根据你所提供的贷款总额、利率、年期而计算出你每月所需的借贷付款。";
				this.mpc_schedule.Text = "还款时间表";
				this.btnMPC.Content = "计算";
				this.mpc_loan.Content = "贷款总额: ";
				this.mpc_interest.Content = "利率: ";
				this.mpc_term_year.Content = "年期: ";
				this.mpc_year_suffix.Content = "年";
				this.mpc_schedule_extra.Content = "每月額外还款: ";
				this.mpc_schedule_loan_start.Content = "始还日期: ";
				this.btnMPC_Schedule.Content = "还款时间表";
				this.txtMPC_Result.Text = "$00.00";

				// what can i afford 
				//
				this.wcia_header.Text = "负担能力计算";
				this.wcia_desired_month_payment.Content = "每月期望还款额: ";
				this.wcia_rate.Content = "利率: ";
				this.wcia_term_year.Content = "年期: ";
				this.wcia_year_suffix.Content = "年";
				this.btnWCIA.Content = "计算";
				this.txtWCIA_Result.Text = "$00.00";

				// how much can i borrow calculator
				//
				this.hmyb_header.Text = "贷款能力计算";
				this.hmyb_salary.Content = "年薪: ";
				this.hmyb_debt_month.Content = "每月负债: ";
				this.hmyb_debt_month_detail.Content = "(只包括十個月未能付清的負債)";
				this.hmyb_loan_term_desire.Text = "期望的贷款规约: ";
				this.hmyb_price.Content = "房屋价格: ";
				this.hmyb_rate.Content = "利率: ";
				this.hmyb_down_payment.Content = "预付金: ";
				this.hmyb_term_year.Content = "年期: ";
				this.hmyb_year_suffix.Content = "年";
				this.hmyb_property_tax_insurance.Text = "预期房产税及房产保险费用(年):";
				this.hmyb_tax.Content = "房产税: ";
				this.hmyb_insurance.Content = "房产保险";
				this.btnHMYB.Content = "计算";
				this.txtHMYB_Result.Text = "$00.00";
			}
			else
			{
				this.Title = "Mortgage Calculators v1.0 - JACK D.";

				this.lang_en.Content = "English";
				this.lang_cn.Content = "Chinese";

				// monthly payment & schedule
				//
				this.mpc_header.Text = "Monthly Payment Calculator & Schedule";
				//this.mpc_tip.Content = "This tool will calculate your monthly payment based on the loan amount, interest rate, and term that you provide.";
				this.mpc_schedule.Text = "Payment Schedule";
				this.btnMPC.Content = "Calculate";
				this.mpc_loan.Content = "Loan Amount: ";
				this.mpc_interest.Content = "Rate: ";
				this.mpc_term_year.Content = "Term: ";
				this.mpc_year_suffix.Content = "years";
				this.mpc_schedule_extra.Content = "Extra Monthly Payment: ";
				this.mpc_schedule_loan_start.Content = "Loam Start Date: ";
				this.btnMPC_Schedule.Content = "Payment Schedule";

				// what can i afford 
				//
				this.wcia_header.Text = "What Can I Afford Calculator";
				this.wcia_desired_month_payment.Content = "Desired Monthly Payment: ";
				this.wcia_rate.Content = "Rate: ";
				this.wcia_term_year.Content = "Term: ";
				this.wcia_year_suffix.Content = "years";
				this.btnWCIA.Content = "Calculate";

				// how much can i borrow calculator
				//
				this.hmyb_header.Text = "How Much Can I Borrow Calculator";
				this.hmyb_salary.Content = "Annual Salary: ";
				this.hmyb_debt_month.Content = "Monthly Debt: ";
				this.hmyb_debt_month_detail.Content = "(Include only loans that won't be paid off in 10 months.)";
				this.hmyb_loan_term_desire.Text = "Loan Terms You Desire: ";
				this.hmyb_price.Content = "Purchase Price: ";
				this.hmyb_rate.Content = "Rate: ";
				this.hmyb_down_payment.Content = "Down Pay: ";
				this.hmyb_term_year.Content = "Term: ";
				this.hmyb_year_suffix.Content = "years";
				this.hmyb_property_tax_insurance.Text = "Property - Expected Taxes / Insurance (yearly):";
				this.hmyb_tax.Content = "Tax: ";
				this.hmyb_insurance.Content = "Insurance";
				this.btnHMYB.Content = "Calculate";

			}
		}
	}
}